package com.nolon.flange.viewmodel

import android.app.Application
import android.content.Context
import android.content.Intent
import android.provider.MediaStore
import android.view.View
import androidx.lifecycle.*
import androidx.preference.PreferenceManager
import com.nolon.flange.extensions.shortToast
import com.nolon.flange.extensions.toast
import com.nolon.flange.model.*
import com.nolon.flange.model.Part.Companion.DIRECTION_LENGTH
import com.nolon.flange.repository.FlangeRepository
import com.nolon.flange.tools.*
import com.nolon.flange.view.buildAlertDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.util.CellRangeAddress
import java.text.SimpleDateFormat
import java.util.*
import com.nolon.flange.R
import n.Init

open class FlangeViewModel(val app: Application, private val projectId: Int) :
    AndroidViewModel(app) {

    private val repository: FlangeRepository by lazy { FlangeRepository(app) }

    lateinit var orderViewModel: OrderViewModel
    lateinit var solutionViewModel: SolutionViewModel
    lateinit var exportViewModel: ExportViewModel

    val isOrderNotEmpty: LiveData<Boolean> by lazy {
        Transformations.map(orderList) {
            it.isNotEmpty()
        }
    }

    val project: LiveData<Project> = repository.getProjectLive(projectId)

    var isProjectChanged: Boolean = false

    val solutions: LiveData<List<RawSolution>> = repository.getRawSolutionsByProjectId(projectId)

    val parts: LiveData<List<Part>> = repository.getPartsByProjectId(projectId)

    val groupedParts: LiveData<Map<Int, List<Part>>> =
        repository.getPartsByProjectIdGroupedBySolutionId(projectId)

    val orderList: LiveData<List<Order>> = repository.getOrdersByProjectId(projectId)

    val isNotEmpty: Boolean get() = orderList.value!!.isNotEmpty()

    val isEmpty: Boolean get() = orderList.value!!.isEmpty()

    val rawInfoList: LiveData<List<RawInfo>> = repository.getRawInfosByProjectId(projectId)

    fun removeOrder(order: Order) {

        isProjectChanged = true

        viewModelScope.launch {
            repository.deleteOrder(order)
            /*
             判断是否需要删除Raw
             order中是否有使用相同Raw的，如果有则不管，如果没有则删除Raw
             */
            order.flange.let { f ->
                val useSameRaw =
                    orderList.value!!.any { it.flange.materialSpec == f.materialSpec && it.flange.actualSpec == f.actualSpec }
                if (!useSameRaw) {
                    val rawToDelete =
                        rawInfoList.value!!.find { it.materialSpec == f.materialSpec && it.actualSpec == f.actualSpec }
                    repository.deleteRawById(rawToDelete!!.id)
                }
            }
        }
    }

    fun updateProject(
        projectName: String? = null,
        orders: List<Order>? = null,
    ) {
        viewModelScope.launch {
            val p = project.value ?: return@launch

            val name = projectName ?: p.name

            val fTypes = orders?.size ?: p.flangeTypes

            val fCount = if (!orders.isNullOrEmpty()) {
                orders.map { it.requiredNumber }.reduce { acc, i -> acc + i }
            } else p.flangeCount

            repository.updateProject(
                repository.getProject(p.id).copy(
                    name = name,
                    flangeTypes = fTypes,
                    flangeCount = fCount,
                    modified = System.currentTimeMillis()
                )
            )
        }
    }

    fun getParts(orders: List<Order>?): List<Part> {
        if (orders == null) return listOf()
        val partList: ArrayList<Part> = arrayListOf()
        orders.forEach { order ->
            val flange = order.flange
            val count = order.requiredNumber

            for (i in 1..count) {
                partList.addAll(flange.getParted(true))
            }
        }
        return partList
    }

    fun getGroupParts(orders: List<Order>): List<FlangePartItem> {
        val groupParts: ArrayList<FlangePartItem> = arrayListOf()
        orders.forEach { order ->
            val flange = order.flange
            val parts: List<Part> = flange.getParted()
            parts.forEach { new ->
                val oneOrNull = groupParts.find { exist ->
                    new.quantity == exist.part.quantity && new.materialSpec == exist.part.materialSpec
                }
                if (oneOrNull != null) {
                    oneOrNull.requiredNum += order.requiredNumber * 2
                } else {
                    groupParts.add(FlangePartItem(new, order.requiredNumber * 2))
                }
            }
        }
        return groupParts
    }

    /**
     * rawinfos 原材料的属性
     */
    fun calculate(v: View, rawInfoList: List<RawInfo>) {
        fun resolveSolution(solution: IntArray, planLength: Int): List<IntArray> {
            val totalRow = solution.size / planLength
            val list = arrayListOf<IntArray>()
            println(solution.toList())
            for (i in 1 until totalRow) {
                val arr = IntArray(planLength)
                System.arraycopy(solution, planLength * i, arr, 0, planLength)
                list.add(arr)
            }
            return list
        }

        fun generate() {
            viewModelScope.launch {

                solutionViewModel.isCalculating.set(View.VISIBLE)

                withContext(Dispatchers.IO) {
                    if (!solutions.value.isNullOrEmpty()) {
                        repository.deleteSolutionsByProjectId(projectId)
                    }
                    val container = arrayListOf<RawSolution>()
                    rawInfoList.forEach { raw ->

                        // 筛选此类型的订单
                        val orders: List<Order>? =
                            orderList.value?.filter { it.flange.materialSpec == raw.materialSpec }
                        val parts = getParts(orders) as ArrayList

                        val groupedParts = getGroupParts(orders!!)

                        val lengths = groupedParts.map { it.part.quantity.toInt() }.toIntArray()
                        val counts = groupedParts.map { it.requiredNum }.toIntArray()

//                        val cutter =
//                            CuttingPlanner(lengths, counts, 5980, 5)
//                        val solution = cutter.solve(200)
//
                        val so = Init.n0099(
                            v.context,
                            lengths,
                            counts,
                            raw.length,
                            raw.maxCombination
                        )

                        val types = lengths.toSet().size

                        val solu = resolveSolution(so, types + 2)

                        val prodList = IntArray(types)
                        System.arraycopy(so, 0, prodList, 0, types)

                        val rawList = arrayListOf<RawSolution>()

                        solu.forEach { fRow ->
                            val used = raw.length - fRow[types]
                            val tail = fRow[types]
                            val usedRate = used.toFloat() / raw.length
                            val r = RawSolution(
                                rawInfo = raw,
                                count = fRow[types + 1],
                                projectId = raw.projectId,
                                tailLength = tail,
                                usageRate = usedRate,
                            )
                            for (i in 0 until types) {
                                for (j in 1..fRow[i]) {
                                    r.partsPlain.add(prodList[i])
                                }
                            }
                            rawList.add(r)
                        }

                        // 先排不需要倒角的，再从小排到大，排序规则一定要满足传递性，对称性……，就是说要穷尽所有情况
                        // 如果排序规则有问题 Comparison method violates its general contract!
                        parts.sortWith { a, b ->
                            when {
                                a.direction != b.direction -> a.direction.compareTo(b.direction)
                                a.quantity == b.quantity -> 0
                                else -> a.quantity.compareTo(b.quantity)
                            }
                        }

                        val total = parts.size                   // 零件一共多少个，下面开始遍历
                        for (index in 1..total) {
                            val part = parts.removeAt(0)   // 从列表里取出第一个，不放回的
                            var placed = false                  // 零件是否安排在原材料上的标识符
                            // 实现break的方式
                            with(placed) loop@{
                                // 遍历一下原材料列表
                                rawList.forEach {
                                    placed = it.mayI(part)  // ifRoom方法用来判断当前这根原材料是否足够放前面取出来的零件
                                    if (placed) return@loop  // 如果已经放进去了，结束循环
                                }
                            }
                        }
                        container.addAll(rawList)
                    }

                    repository.saveSolutions(container)

                    solutionViewModel.isCalculating.set(View.GONE)
                }
            }
        }

        isProjectChanged = true

        // 先保存一下RawInfo
        viewModelScope.launch {
            repository.updateRaws(rawInfoList)
        }

        if (!solutions.value.isNullOrEmpty()) {
            buildAlertDialog(
                v.context,
                "是否要重新计算？",
                "重新计算会覆盖当前方案。",
                "确定",
                "取消"
            ) {
                generate()
            }.show()
        } else generate()
    }

    fun saveOrders(orders: List<Order>) = viewModelScope.launch {
        repository.insertOrderItems(orders)
    }

    fun clearOrders() {
        viewModelScope.launch {
            orderList.value?.forEach {
                repository.deleteOrder(it)
            }
        }
    }

    fun addOrUpdateOrder(view: View) {
        viewModelScope.launch {
            val order = orderViewModel.getOrder(view)?.copy(projectId = projectId)
            order?.let {
                if (it.id == 0) {
                    repository.insertOrderItem(order)
                    toast(view.context, view.context.getString(R.string.add_success))
                } else {
                    repository.updateOrder(order)
                    view.shortToast(R.string.modify_success)
                }
                // 更新RawInfo列表
                /*
                目前的Raw里有没有适合这个Flange的，
                有则不管，没有则新建，
                 */
                it.flange.let { flange ->
                    val existed = rawInfoList.value?.any { rawInfo ->
                        rawInfo.materialSpec == flange.materialSpec && rawInfo.actualSpec == flange.actualSpec
                    }
                    if (existed != null && !existed) {
                        repository.insertRaw(
                            RawInfo(
                                id = 0,
                                projectId = projectId,
                                materialSpec = flange.materialSpec,
                                actualSpec = flange.actualSpec
                            )
                        )
                    }
                }
            }
        }
    }


    fun populateResult(project: Project?) {
        viewModelScope.launch {
            if (project == null) return@launch
            if (project.rawCount == 0 && project.usageRate == 1f && project.totalCost == 0f) return@launch
            with(solutionViewModel) {
                resultVisible.set(View.VISIBLE)
                val str1 = StringBuilder().apply {
                    append("${project.flangeCount} 个法兰（${project.flangeTypes}种）")
                    append("，零件一共${project.flangeCount * 4}个;")
                }
                flangeAndPartCount.set(str1.toString())

                str1.clear().apply {
                    append("生成排料图 ${project.solutionCount} 个")
                    append("，一共使用角钢 ${project.rawCount} 条;")
                }
                solutionAndRawCount.set(str1.toString())

                str1.clear().apply {
                    append("整体利用率${project.usageRate.percent2}")
                    append("，总成本${project.totalCost.digit2}元")
                    append("，边角料浪费金额${(project.totalCost * (1 - project.usageRate)).digit2}元。")
                }
                usageRateAndCost.set(str1.toString())
            }
        }
    }

    fun editOrder(order: Order) = orderViewModel.editOrder(order)

    fun removeProject() {
        viewModelScope.launch {
            repository.deleteProjectById(projectId)
        }
    }

    fun saveToExcel(context: Context) {
        viewModelScope.launch {

            // 检查一下有没有打勾🐕
            with(exportViewModel) {
                if (!(exportPlan.get()!! || exportDetails.get()!! || exportFlangeList.get()!!)) {
                    toast(context, "请选择要导出的内容！")
                    return@launch
                }
            }

            exportViewModel.isBtnEnable.set(false)

            val exportHoles = PreferenceManager.getDefaultSharedPreferences(context)
                .getBoolean(context.getString(R.string.pref_export_hole), true)

            val uri = withContext(Dispatchers.IO) {
                val workbook = HSSFWorkbook()
                val colCount = if (exportHoles) 11 else 5

                val fileName = if (exportViewModel.projectName.get().isNullOrEmpty()) {
                    project.value?.name
                } else {
                    exportViewModel.projectName.get()?.trim()
                }

                if (exportViewModel.exportPlan.get()!!) {
                    val planSheet = workbook.createSheet("排料表")
                    var currRow = 0
                    with(planSheet) {
                        // 标题栏
                        val titleRow = createRow(currRow++)
                        titleRow.height = 3 * 256
                        for (i in 0 until colCount) {
                            titleRow.createCell(i).setCellStyle(workbook.mergeTitleStyle)
                        }
                        val titleRange = CellRangeAddress(0, 0, 0, colCount - 1)
                        addMergedRegion(titleRange)
                        val titleCell = titleRow.getCell(0)
                        titleCell.setCellValue("角钢法兰排料表")
                        // 项目名，日期
                        val nameRow = createRow(currRow++)
                        for (i in 0 until colCount) {
                            nameRow.createCell(i).setCellStyle(workbook.headerRow)
                        }
                        val nameRange = CellRangeAddress(currRow - 1, currRow - 1, 0, colCount - 1)
                        addMergedRegion(nameRange)
                        nameRow.getCell(0).setCellValue("工程名：$fileName")

                        val dateRow = createRow(currRow++)
                        for (i in 0 until colCount) {
                            dateRow.createCell(i).setCellStyle(workbook.headerRow)
                        }
                        val dateRange = CellRangeAddress(currRow - 1, currRow - 1, 0, colCount - 1)
                        addMergedRegion(dateRange)
                        val today = today("yyyy年MM月dd日")
                        dateRow.getCell(0).setCellValue("日期：${today}")
                    }

                    // 原料统计信息
                    with(planSheet) {
                        currRow++
                        val reducedRaws = solutions.value!!.map { it.rawInfo }.toSet()
                        // 标题
                        val headRow = createRow(currRow++).apply {
                            var r = 0
                            createCell(r++).setCellValue("序号")
                            createCell(r++).setCellValue("材料规格")
                            createCell(r++).setCellValue("长度")
                            createCell(r).setCellValue("用量")
                            forEach { it.cellStyle = workbook.headerRow }
                            height = 2 * 256
                        }
                        // 内容
                        reducedRaws.forEachIndexed { i, raw ->
                            val contentRow = createRow(currRow++).apply {
                                val one = solutions.value!!.find { it.rawInfo == raw }
                                val count =
                                    solutions.value!!.filter { it.rawInfo == raw }.map { it.count }
                                        .reduce { acc, i -> acc + i }
                                var r = 0
                                createCell(r++).setCellValue("${i + 1}")
                                createCell(r++).setCellValue(raw.actualSpec.toDouble())
                                createCell(r++).setCellValue(one!!.rawInfo.length.toDouble())
                                createCell(r).setCellValue("${count}根")
                                forEach { it.cellStyle = workbook.contentRow }
                                height = 2 * 256
                            }
                        }
                    }
                    // 排料图
                    solutions.value!!.forEachIndexed { i, solution ->
                        currRow++ //空出一行

                        val titleRow = planSheet.createRow(currRow++).apply {
                            height = if (exportHoles) 3 * 256 else 5 * 256
                            for (j in 0 until colCount) {
                                createCell(j).setCellStyle(workbook.headerRow)
                            }
                            val range = CellRangeAddress(currRow - 1, currRow - 1, 0, colCount - 1)
                            planSheet.addMergedRegion(range)
                            val solutionStr =
                                "排料图${i + 1}#；" + "材料型号${solution.rawInfo.materialSpec}；" +
                                        "长度${solution.rawInfo.length}；数量${solution.count}；" +
                                        "利用率${solution.usageRate.percent2}；" +
                                        "剩余${solution.tailLength} "
                            getCell(0).setCellValue(solutionStr)

                        }

                        if (exportHoles) { // create two row
                            val headerRow1 = planSheet.createRow(currRow++).apply {
                                height = 2 * 256
                                for (j in 0 until colCount) {
                                    createCell(j).setCellStyle(workbook.headerRow)
                                }
                            }
                            val headerRow2 = planSheet.createRow(currRow++).apply {
                                height = 2 * 256
                                for (j in 0 until colCount) {
                                    createCell(j).setCellStyle(workbook.headerRow)
                                }
                            }
                            for (j in 0..4) {
                                val range = CellRangeAddress(currRow - 2, currRow - 1, j, j)
                                planSheet.addMergedRegion(range)
                            }
                            for (j in 0..1) {
                                val range =
                                    CellRangeAddress(currRow - 2, currRow - 2, 5 + j * 3, 7 + j * 3)
                                planSheet.addMergedRegion(range)
                            }
                            headerRow1.apply {
                                getCell(0).setCellValue("序号")
                                getCell(1).setCellValue("零件长度")
                                getCell(2).setCellValue("数量")
                                getCell(3).setCellValue("用途")
                                getCell(4).setCellValue("倒角")
                                getCell(5).setCellValue("大孔")
                                getCell(8).setCellValue("小孔")
                            }
                            headerRow2.apply {
                                getCell(5).setCellValue("数量")
                                getCell(6).setCellValue("边距")
                                getCell(7).setCellValue("中心距")
                                getCell(8).setCellValue("数量")
                                getCell(9).setCellValue("边距")
                                getCell(10).setCellValue("中心距")
                            }
                        } else {
                            val headerRow = planSheet.createRow(currRow++).apply {
                                var r = 0
                                createCell(r++).setCellValue("序号")
                                createCell(r++).setCellValue("零件长度")
                                createCell(r++).setCellValue("数量")
                                createCell(r++).setCellValue("用途")
                                createCell(r).setCellValue("倒角")
                                forEach { it.cellStyle = workbook.headerRow }
                                height = 2 * 256
                            }
                        }

                        val parts = groupedParts.value!![solution.id]
                        val partsSet = arrayListOf<Part>().apply {
                            parts!!.forEach { src ->
                                if (!this.any { des -> src == des }) {
                                    add(src)
                                }
                            }
                        }

                        partsSet.forEachIndexed { j, p ->
                            val row = planSheet.createRow(currRow++).apply {
                                var r = 0
                                createCell(r++).setCellValue((j + 1).toDouble())
                                createCell(r++).setCellValue(p.quantity.toDouble())
                                createCell(r++).setCellValue(parts!!.count { it == p }.toDouble())
                                createCell(r++).setCellValue(if (p.direction == DIRECTION_LENGTH) "长料" else "短料")
                                createCell(r++).setCellValue(if (p.rounding) "是" else "否")
                                if (exportHoles) {
                                    createCell(r++).setCellValue(p.bigHoles.toDouble())
                                    createCell(r++).setCellValue(p.bigPadding.toDouble())
                                    createCell(r++).setCellValue(p.bigDistance.toDouble())
                                    createCell(r++).setCellValue(p.smallHoles.toDouble())
                                    createCell(r++).setCellValue(p.smallPadding.toDouble())
                                    createCell(r).setCellValue(p.smallDistance.toDouble())
                                }
                            }
                            row.forEach { it.cellStyle = workbook.contentRow }
                            row.height = 2 * 256
                        }
                    }

                    planSheet.setColumnWidth(0, 6 * 256) //序号
                    planSheet.setColumnWidth(1, 12 * 256) // 零件长度
                    planSheet.setColumnWidth(2, 9 * 256) // 数量
                    planSheet.setColumnWidth(3, 9 * 256)  // 用途
                    planSheet.setColumnWidth(4, 6 * 256)  // 倒角
                    if (exportHoles) {
                        planSheet.setColumnWidth(5, 6 * 256)  // 数量
                        planSheet.setColumnWidth(6, 6 * 256)  // 边距
                        planSheet.setColumnWidth(7, 9 * 256)  // 中心距
                        planSheet.setColumnWidth(8, 6 * 256)  // 数量
                        planSheet.setColumnWidth(9, 6 * 256)  // 边距
                        planSheet.setColumnWidth(10, 9 * 256)  // 中心距
                    }
                }

                if (exportViewModel.exportDetails.get()!!) {
                    val partsSheet = workbook.createSheet("下料明细")
                    var currRow = 0

                    val headerRow = partsSheet.createRow(currRow++).apply {
                        var r = 0
                        createCell(r++).setCellValue("排料图号")
                        createCell(r++).setCellValue("序号")
                        createCell(r++).setCellValue("零件长度")
                        createCell(r++).setCellValue("材料规格")
                        createCell(r++).setCellValue("实际规格")
                        createCell(r++).setCellValue("用途")
                        createCell(r++).setCellValue("倒角")
                        if (exportHoles) {
                            createCell(r++).setCellValue("大孔数量")
                            createCell(r++).setCellValue("大孔边距")
                            createCell(r++).setCellValue("大孔中心距")
                            createCell(r++).setCellValue("小孔数量")
                            createCell(r++).setCellValue("小孔边距")
                            createCell(r).setCellValue("小孔中心距")
                        }
                        forEach { it.cellStyle = workbook.headerRow }
                        height = 2 * 256
                    }

                    solutions.value!!.forEachIndexed { i, solution ->
                        groupedParts.value!![solution.id]!!.forEachIndexed { j, p ->
                            val row = partsSheet.createRow(currRow++).apply {
                                var r = 0
                                createCell(r++).setCellValue("${(i + 1)}#")
                                createCell(r++).setCellValue((j + 1).toDouble())
                                createCell(r++).setCellValue(p.quantity.toDouble())
                                createCell(r++).setCellValue(p.materialSpec)
                                createCell(r++).setCellValue(p.actualSpec.toDouble())
                                createCell(r++).setCellValue(if (p.direction == DIRECTION_LENGTH) "长料" else "短料")
                                createCell(r++).setCellValue(if (p.rounding) "是" else "否")
                                if (exportHoles) {
                                    createCell(r++).setCellValue(p.bigHoles.toDouble())
                                    createCell(r++).setCellValue(p.bigPadding.toDouble())
                                    createCell(r++).setCellValue(p.bigDistance.toDouble())
                                    createCell(r++).setCellValue(p.smallHoles.toDouble())
                                    createCell(r++).setCellValue(p.smallPadding.toDouble())
                                    createCell(r).setCellValue(p.smallDistance.toDouble())
                                }
                            }
                            row.forEach { it.cellStyle = workbook.contentRow }
                            row.height = 2 * 256
                        }
                    }

                }

                if (exportViewModel.exportFlangeList.get()!!) {
                    val orderSheet = workbook.createSheet("订单")

                    var currRow = 0

                    val headerRow = orderSheet.createRow(currRow++).apply {
                        createCell(0).setCellValue("序号")
                        createCell(1).setCellValue("法兰长")
                        createCell(2).setCellValue("法兰宽")
                        createCell(3).setCellValue("长加")
                        createCell(4).setCellValue("宽加")
                        createCell(5).setCellValue("角钢规格")
                        createCell(6).setCellValue("实际规格")
                        createCell(7).setCellValue("长料倒角")
                        createCell(8).setCellValue("个数")
                        forEach { it.cellStyle = workbook.headerRow }
                        height = 2 * 256
                    }

                    orderList.value?.forEach {
                        val row = orderSheet.createRow(currRow++).apply {
                            val f = it.flange
                            createCell(0).setCellValue((currRow - 2).toDouble())
                            createCell(1).setCellValue(f.length.toDouble())
                            createCell(2).setCellValue(f.width.toDouble())
                            createCell(3).setCellValue(f.extraLength.toDouble())
                            createCell(4).setCellValue(f.extraWidth.toDouble())
                            createCell(5).setCellValue(f.materialSpec)
                            createCell(6).setCellValue(f.actualSpec.toDouble())
                            createCell(7).setCellValue(if (f.hasRounding) "是" else "否")
                            createCell(8).setCellValue(it.requiredNumber.toDouble())

                            forEach { it.cellStyle = workbook.contentRow }
                            height = 2 * 256
                        }
                    }
                }

                val date = SimpleDateFormat(
                    exportViewModel.exportFilePattern.get(),
                    Locale.getDefault()
                ).format(Date())

                saveXlsFile(context, workbook, fileName!! + date)
            }

            exportViewModel.isBtnEnable.set(true)

            if (uri == null) return@launch
            buildAlertDialog(
                context = context,
                title = "文件已导出",
                message = "文件已导出在Download文件夹，是否打开查看？",
                positiveStr = "打开",
                negativeStr = "取消"
            ) {
                val intent = Intent(Intent.ACTION_VIEW).apply {
                    setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    setDataAndType(uri, "application/vnd.ms-excel")
                }

                try {
                    val cursor =
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                            context.contentResolver.query(
                                uri,
                                arrayOf<String>(
                                    MediaStore.Files.FileColumns._ID,
                                    MediaStore.Files.FileColumns.DATA
                                ), null, null
                            )
                        } else {
                            null
                        }
                    cursor?.moveToFirst()
                    val filePath =
                        cursor?.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
                    val intent2 = OpenFiles.getExcelFileIntent(filePath)
                    context.startActivity(intent)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }.show()
        }
    }
}

